﻿
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections;
using System.Linq;
using System.Net;
using System.Security.Claims;

namespace DefenseQuestion.WebAPI.Filters
{
    public class CustomerAuthorizationFilterAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if(context.ActionDescriptor.EndpointMetadata.Any(em=>em is Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute))
            {
                return;
            }
            //string DisplayName=context.ActionDescriptor.DisplayName;
            string AttributeRouteInfo ="/"+ context.ActionDescriptor.AttributeRouteInfo.Template;

            bool IsLogin=context.HttpContext.User.Identity.IsAuthenticated;
            if (!IsLogin)
            {
                context.Result = new StatusCodeResult((int)HttpStatusCode.Unauthorized);
            }
            else
            {
                if (context.ActionDescriptor.EndpointMetadata.Any(em => em is AuthorizeAttribute))
                {
                    return;
                }
              //  var menuRepository = context.HttpContext.RequestServices.GetService<IBaseRepository<Menu>>();
                //var roleMenuRepository = context.HttpContext.RequestServices.GetService<IBaseRepository<RoleMenu>>();
             //   var MenuRoleId = roleMenuRepository.Queryable().Where(x => menuRepository.Queryable().Where(x => x.MenuInterface == AttributeRouteInfo).Select(x => x.MenuId).Contains(x.MenuId)).Select(x => x.RoleId).ToList();
               
                string UserName=context.HttpContext.User.Identity.Name;
                var claims = context.HttpContext.User.Claims;
                var RoleId = claims.First(m=>m.Type==ClaimTypes.Role).Value.Split(',');
                int [] userRoleId = Array.ConvertAll(RoleId, m => Convert.ToInt32(m));
              //  if (!userRoleId.Any(m => MenuRoleId.Contains(m)))
                {
                    context.Result=new StatusCodeResult((int)HttpStatusCode.Forbidden);
                }
            }
        }
    }
}
